package com.frog.service.friend.service.relation;


import com.alibaba.fastjson.JSON;
import com.frog.service.friend.common.CommonStringUtil;
import com.frog.service.friend.mapper.FriendImportantMessageDOMapper;
import com.frog.service.friend.model.RelationModel;
import com.frog.service.friend.model.domain.FriendFollowingRelationshipDO;
import com.frog.service.friend.model.domain.FriendImportantMessageDO;
import com.frog.service.friend.service.cache.FriendFollowService;
import com.frog.service.friend.service.friendList.MaintainRelationService;
import com.frog.service.friend.utils.FriendRelationshipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * 拉黑关系实例
 */
@Slf4j
@Service("blockRelationInstance")
public class BlockRelation implements Relation {

    @Autowired
    private FriendFollowService friendFollowService;
    @Autowired
    private FriendImportantMessageDOMapper friendImportantMessageDOMapper;
    @Autowired
    private MaintainRelationService maintainRelationService;

    /**
     * 拉黑好友
     *
     * @param userId       主动发起人
     * @param friendUserId 被动拉黑人
     * @return userId已经拉黑friendUserId完成状态
     */
    @Override
    public boolean establish(Integer userId, Integer friendUserId) {
        Long id = FriendRelationshipUtil.processRelationId(userId, friendUserId);
        if (id == null || id == 0) return false;
        FriendFollowingRelationshipDO f = friendFollowService.select(String.valueOf(id));
        return f == null ? initAddBlock(id, userId, friendUserId) : renewAddBlock(id, userId, friendUserId, f);
    }

    /**
     * 解除拉黑好友
     *
     * @param userId       主动发起人
     * @param friendUserId 被动拉黑人
     * @return serId已经拉黑friendUserId完成状态
     */
    @Override
    public boolean termination(Integer userId, Integer friendUserId) {
        Long id = FriendRelationshipUtil.processRelationId(userId, friendUserId);
        if (id == null || id == 0) return false;
        FriendFollowingRelationshipDO f = friendFollowService.select(String.valueOf(id));
        return renewCancelBlock(id, userId, friendUserId, f);
    }


    /**
     * 初始化拉黑关系
     */
    private boolean initAddBlock(Long id, Integer userId, Integer friendUserId) {
        // 添加好友关系表和缓存
        FriendFollowingRelationshipDO f = FriendFollowingRelationshipDO.builder().id(id)
                .fromUserId(userId).toUserId(friendUserId)
                .createTime(System.currentTimeMillis()).updateTime(System.currentTimeMillis())
                .followStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .bestStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .blockStatus(CommonStringUtil.FriendBothStatus.sendConcerned)
                .cancelStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .build();
        if (!friendFollowService.save(id, f)) return false;

        // 保存friendList
        RelationModel r = new RelationModel(id, userId, userId, friendUserId, CommonStringUtil.FriendBothStatus.notConcerned, true);
        maintainRelationService.addBlock(r);

        // 添加好友记录信息表
        FriendImportantMessageDO im = FriendImportantMessageDO.builder()
                .fromUserId(userId).toUserId(friendUserId)
                .createTime(System.currentTimeMillis())
                .messageType(CommonStringUtil.FriendBothStatus.unilateralAttention)
                .build();
        Integer status = 0;
        try {
            status = friendImportantMessageDOMapper.insertData(im);
        } catch (Exception exception) {
            log.error("initAddBlock friendImportantMessageDOMapper exception: id=={} im=={} ", id, JSON.toJSONString(im), exception);
        }
        return status != 0;
    }


    /**
     * 添加拉黑状态,更新好友关系
     */
    private boolean renewAddBlock(Long id, Integer userId, Integer friendUserId, FriendFollowingRelationshipDO f) {
        if (f == null) return false;
        if (userId == null || friendUserId == null) return false;

        // 获取到添加拉黑关系后的state状态
        Integer fromUserId = f.getFromUserId();
        Integer toUserId = f.getToUserId();
        RelationModel r = new RelationModel(id, userId, fromUserId, toUserId, f.getBlockStatus(), true);
        if (!r.isSuccessStatus()) return false;


        // 更新拉黑关系
        Map<String, Object> fm = new HashMap<>();
        fm.put("block_status", r.getStatusLater());
        fm.put("update_time", System.currentTimeMillis());
        if (!friendFollowService.modify(id, fm)) return false;

        // 更新成功后,更新friendList
        maintainRelationService.addBlock(r);

        // 修改记录添加数据库
        FriendImportantMessageDO im = FriendImportantMessageDO.builder()
                .fromUserId(userId).toUserId(friendUserId)
                .createTime(System.currentTimeMillis())
                .messageType(CommonStringUtil.FriendBothStatus.unilateralAttention)
                .build();
        Integer status = 0;
        try {
            status = friendImportantMessageDOMapper.insertData(im);
        } catch (Exception e) {
            log.error("renewAddBlock friendImportantMessageDOMapper exception: id=={} im=={} ", id, JSON.toJSONString(im), e);
        }
        return status != 0;
    }


    /**
     * 取消拉黑状态,更新好友关系
     */
    private boolean renewCancelBlock(Long id, Integer userId, Integer friendUserId, FriendFollowingRelationshipDO f) {
        if (f == null) return false;
        if (userId == null || friendUserId == null) return false;

        // 获取到取消拉黑关系后的state状态
        Integer fromUserId = f.getFromUserId();
        Integer toUserId = f.getToUserId();
        RelationModel r = new RelationModel(id, userId, fromUserId, toUserId, f.getBlockStatus(), false);
        if (!r.isSuccessStatus()) return false;


        // 更新数据库和缓存状态值
        Map<String, Object> fm = new HashMap<>();
        fm.put("block_status", r.getStatusLater());
        fm.put("update_time", System.currentTimeMillis());
        if (!friendFollowService.modify(id, fm)) return false;

        // 更新关系成功后,更新friendList
        maintainRelationService.delBlock(f, r);
        return true;
    }


}